When you’re training models, preprocessing and training can take forever. With a large dataset, two or three days can disappear before you know it. Discover a bug after two days and you get to start all over again. Here’s how to use profilers to find what’s slowing your program down.
The simple, easy-to-use Line Profiler
Line Profiler is somewhat invasive: you need to change your code manually.
First, the simplest step: install it.
1 | pip install line_profiler |
After installation, add @profile to your program as shown below. Some editors may warn that they can’t find the symbol.
1 | from line_profiler import profile |
Then, instead of running it directly, run:
1 | kernprof -l <filename>.py |
kernprof produces profile files, but they aren’t plain ASCII files you can simply open. Use line_profiler to print their contents:
1 | $ python -m line_profiler .\exp.py.lprof |
Easy to read, isn’t it? The annoying part is having to add @profile by hand to every function you want to inspect.
cProfile - More detail
cProfile is even more detailed and can even profile at the C level.
It can be used invasively or non-invasively.
For non-invasive use:
1 | python -m cProfile -o myLog.profile <myScript.py> arg1 arg2 |
Here -o specifies the name of the saved profile file; you can omit it if you do not want one. The result looks like this:
1 | 5 function calls in 0.001 seconds |
If you want to see a flame graph, you need to export the profile file:
1 | flameprof pipeline.prof > pipeline.svg |
The following produces a call graph, which is also fairly intuitive:
1 | gprof2dot -f pstats myLog.profile -o callingGraph.dot |
py-spy: Super convenient
A flame graph takes two commands with cProfile. Want one command instead? py-spy can do it without modifying your code:
1 | py-spy record -o profile.svg -- python myprogram.py |
torch.profiler
PyTorch includes a profiler for finding bottlenecks in neural-network computation. In my case, though, the bottleneck wasn’t the GPU at all—it was a single CPU core. How embarrassing.
1 | from torch.profiler import profile, record_function, ProfilerActivity |